package com.github.starry.fw.generator.java.generator.command;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;

import com.github.starry.fw.generator.java.api.GeneratorConfig;
import com.github.starry.fw.generator.java.generator.AbstractCommand;
import com.github.starry.fw.generator.java.generator.JavaModifierEnum;

public class JavaMethod extends AbstractCommand {

    private JavaModifierEnum modifier = JavaModifierEnum.PRIVATE;

    private JavaMethodReturn returnType;

    private String methodName;

    private List<JavaMethodParam> params = new ArrayList<JavaMethodParam>();

    private String methodComment;


    public JavaMethod(JavaModifierEnum modifier, JavaMethodReturn returnType,
            String methodName, List<JavaMethodParam> params, String methodComment) {
        super();
        this.modifier = modifier;
        this.returnType = returnType;
        this.methodName = methodName;
        this.params = params;
        this.methodComment = methodComment;
    }

    public JavaMethod(JavaModifierEnum modifier, JavaMethodReturn returnType,
            String methodName,  String methodComment) {
        super();
        this.modifier = modifier;
        this.returnType = returnType;
        this.methodName = methodName;
        this.methodComment = methodComment;
    }

    public void addParam(JavaMethodParam command) {
        params.add(command);
    }

    @Override
    protected String getCommandLine(GeneratorConfig config){

        List<String> paramList = new ArrayList<String>();
        for(JavaMethodParam param : params) {
            paramList.add(param.getCommandLine(config));
        }

        String parameter = StringUtils.join(paramList,", ");

        return StringUtils.join(new String[] { modifier.toString(), returnType.getCommandLine(config), methodName, "("+ parameter+ ")" }, " ");
    }


    @Override
    public List<String> getComment(GeneratorConfig config) {
        MultiComment multiComment = new MultiComment(methodComment);

        for(JavaMethodParam param : params) {
            multiComment.addBlockCommand(param.getJavaDoc());
        }

        AbstractCommand returnTypeCommand = returnType.getJavaDoc();
        if(returnTypeCommand != null)
        multiComment.addBlockCommand(returnTypeCommand);

        return multiComment.getSourceLines(config);
    }

    @Override
    public List<String> getImports() {

        List<String> importList = super.getImports();

        for(JavaMethodParam param : params) {
            importList.addAll(param.getImports());
        }
        importList.addAll(returnType.getImports());

        return importList;
    }

}
